package com.example.experiment6.model;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.example.experiment6.bean.QRcodeReturn;
import com.example.experiment6.bean.ResultItem;

import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.internal.observers.DisposableLambdaObserver;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.fastjson.FastJsonConverterFactory;

public class QRcodeModel {
    QRcodeApi.QRcodeServer qRcodeServer=null;
    public QRcodeModel(){
        Retrofit retrofit=new Retrofit.Builder().baseUrl(QRcodeApi.BASE_URL)
                .addConverterFactory(FastJsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        qRcodeServer=retrofit.create(QRcodeApi.QRcodeServer.class);
    }
    public void getQRcode(String text, ImageView imageView) {
        qRcodeServer.getQRcode(QRcodeApi.APP_KEY,text)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DisposableObserver<QRcodeReturn>() {
                    @Override
                    public void onNext(QRcodeReturn qRcodeReturn) {
                        if (qRcodeReturn.getReason().equalsIgnoreCase("success")) {
                            String base64 = qRcodeReturn.getResult().getBase64_image();
                            byte [] input= Base64.getDecoder().decode(base64);
                            Bitmap bitmap;
                            bitmap= BitmapFactory.decodeByteArray(input,0,input.length);
                            System.out.println(base64);
                            imageView.setImageBitmap(bitmap);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
